/**
 *  myuitl/get_jsapi_ticket.js
 *  获取 jsapi_ticket
*/

'use strict';


const getAccessToken = require('./get_accesstoken.js');

const axios = require('axios');

//有效期  number
const EXPIRE = 7000*1000;

//最近一次获取 aceess_token 时间
let start_at = 0;

// Promise
let p = null;


let ticket_data = {} ;



// 异常处理交给调用者,调用结果也交给调用者
// 除非网络异常，不然不会throw error

/**
 * 
{
  "errcode":0,
  "errmsg":"ok",
  "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
  "expires_in":7200
}
 */
module.exports = async (appid, appsecret)=>{


     //正在获取中
    if(p){


       	let { data } = await p;
            
        return data


    //过期了 或 上次有误
    }else if(Date.now()-start_at>EXPIRE || ticket_data.errcode ){



        let accesstoken_data = await getAccessToken(appid, appsecret);


        //无access_token 说明有异常 马上返回
        if(!accesstoken_data.access_token){

        	return accesstoken_data
        }

        let {access_token} = accesstoken_data;


       	p = axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`);


        try{

            let { data } = await p;

            ticket_data = data;

            if(data.ticket){

            	start_at = Date.now();
            }
          

        }catch(e){

            throw e

        }finally{

        	p = null;
        }

    }


    return ticket_data



}